package com.googlecode.perfectable.messageable;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;

public class StandardServer implements Server {
	private final ServerSocket socket;
	private final ConnectionHandler handler;
	
	StandardServer(ServerSocket socket, ConnectionHandler handler) {
		this.socket = socket;
		this.handler = handler;
	}
	
	@Override
	public void acceptingLoop(Executor clientExecutor) {
		while(!this.socket.isClosed()) {
			accept(clientExecutor);
		}
	}
	
	@SuppressWarnings("resource")
	public void accept(Executor clientExecutor) {
		Socket clientSocket;
		try {
			clientSocket = this.socket.accept();
		}
		catch(IOException e) {
			throw new RuntimeException(e);
		}
		Endpoint endpoint = this.handler.handleConnection(clientSocket);
		clientExecutor.execute(() -> endpoint.receivingLoop());
	}
	
}
